import Vue from 'vue';
import VueRouter from 'vue-router';
import store from "../store";
import Home from '../views/Home.vue';
import MyInfo from "../views/MyInfo";
import MyAddr from "../views/MyAddr";
import MyPkg from "../views/MyPkg";
import PkgSearch from "../views/PkgSearch";
import PkgProcess from "../views/PkgProcess";
import About from '../views/About.vue'
import SignIn from "../views/SignIn";
import SignUp from "../views/SignUp";
import PkgNew from "../views/PkgNew";
import Auth from "../views/Auth";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: '首页',
    component: Home,
    meta: {
      requireAuth: false
    }
  },
  {
    path: '/my/info',
    name: '我的信息',
    component: MyInfo,
    meta: {
      requireAuth: true,
      authLevel: 3,
    }
  },
  {
    path: '/my/addr',
    name: '我的地址',
    component: MyAddr,
    meta: {
      requireAuth: true,
      authLevel: 3,
    }
  },
  {
    path: '/my/pkg',
    name: '我的包裹',
    component: MyPkg,
    meta: {
      requireAuth: true,
      authLevel: 3,
    }
  },
  {
    path: '/pkg/new',
    name: '包裹新建',
    component: PkgNew,
    meta: {
      requireAuth: true,
      authLevel: 3,
    }
  },
  {
    path: '/pkg/search',
    name: '包裹查询',
    component: PkgSearch,
    meta: {
      requireAuth: true,
      authLevel: 3,
    }
  },
  {
    path: '/pkg/process',
    name: '包裹处理',
    component: PkgProcess,
    meta: {
      requireAuth: true,
      authLevel: 2,
    }
  },
  {
    path: '/auth',
    name: '权限',
    component: Auth,
    meta: {
      requireAuth: true,
      authLevel: 1,
    }
  },
  {
    path: '/about',
    name: '关于',
    component: About,
    meta: {
      requireAuth: false
    }
  },
  {
    path: '/sign-up',
    name: '注册',
    component: SignUp,
    meta: {
      requireAuth: false
    }
  },
  {
    path: '/sign-in',
    name: '登录',
    component: SignIn,
    meta: {
      requireAuth: false
    }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    if (!store.state.user) {
      Vue.prototype.$message.error('请先登录!')
      next({path: '/sign-in'})
    } else if (to.meta.authLevel === 3) next()
    else {
      if (store.state.user.type > to.meta.authLevel) {
        console.log(store.state.user.type)
        Vue.prototype.$message.error('您的权限不足!')
      } else next()
    }
  } else next()
})

export default router
